<?php

class CS_View extends CS_Core
{
	public $theme;

	public $content;
	
	public $title = 'Welcom to csFrame';

	public $vars = array();

	public function setTheme($theme = null)
	{
		if(!empty($theme))
		{
			$this->theme = $theme;
		}
	}

	public function setVars($data = array())
	{
		if(!empty($data))
		{
			foreach($data as $key => $value)
			{
				$this->{$key} = $value;
			}
		}

		unset($this->vars);
	}

	public function loadView($controller, $view)
	{
		$path = 'design'.DS.$this->theme.DS.'views'.DS.$controller.DS.$view.VIEW_EXT;

		try {

			if(file_exists(PATH.$path))
			{
				ob_start();
					require_once($path);
				$this->content = ob_get_clean();
			} else {
				throw new CS_Error_Exception("The view wasn't found : ".$path);
			}
		} catch(CS_Error_Exception $e){
			$e->printError();
		}

		return $this->content;
	}

	public function loadLayout($layout = 'default')
	{
		$path = 'design'.DS.$this->theme.DS.'layouts'.DS.$layout.VIEW_EXT;

		try {

			if(file_exists(PATH.$path))
			{
					require_once($path);
			} else {
				throw new CS_Error_Exception("The layout wasn't found : ".$path);
			}
		} catch(CS_Error_Exception $e)
		{
			$e->printError();
		}
	}

	public function charSet()
	{

	}

	public function title()
	{
		return $this->title;
	}

	public function content()
	{
		return $this->content;
	}

	public function addScript($scripts = null)
	{
		if(!empty($scripts))
		{
			if(is_string($scripts))
			{
				if(!$this->checkExt($scripts, 'js'))
				{
					$scripts = $scripts.'.js';
				}
				return '<script type="text/javascript" src="'.$this->baseUrl('js').$scripts.'"></script>';
			} elseif(is_array($scripts)) {
				$data = '';
				foreach($scripts as $script)
				{
					if(!$this->checkExt($script, 'js'))
					{
						$script = $script.'.js';
					}
					$data .= '<script type="text/javascript" src="'.$this->baseUrl('js').$script.'"></script>';
				}
			}

			return $data;
		}
	}

	public function addStyle($styles = null)
	{
		if(!empty($styles))
		{
			if(is_string($styles))
			{
				if(!$this->checkExt($styles, 'css'))
				{
					$scripts = $styles.'.css';
				}
				return '<link type="text/css" rel="stylesheet" href="'.$this->baseUrl('css').$styles.'" />';
			} elseif(is_array($styles)) {
				$data = '';
				foreach($styles as $style)
				{
					if(!$this->checkExt($style, 'css'))
					{
						$style = $style.'.css';
					}
					$data .= '<link type="text/css" rel="stylesheet" href="'.$this->baseUrl('css').$style.'" />';
				}
			}

			return $data;
		}
	}

	public function checkExt($script, $type = 'js')
	{
		$ext = substr($script, strrpos($script, '.'));

		if($ext != $type)
		{
			return false;
		} else {
			return true;
		}
	}

	public function baseUrl($type = null)
	{
		return CS_Application::baseUrl($type);
	}
}
